package util

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"html"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

func GetMD5Hash(text string) string {
	hash := md5.Sum([]byte(text))
	return hex.EncodeToString(hash[:])
}

func RoundToDay(toRound time.Time) time.Time {
	return time.Date(toRound.Year(), toRound.Month(), toRound.Day(), 0, 0, 0, 0, toRound.Location())
}

/* t1-t2 */
func TwoDayDuration(t1 time.Time, t2 time.Time) int {
	d := RoundToDay(t1).Sub(RoundToDay(t2))
	return int(d.Hours() / 24)
}

// 27.6701 -> "27.7"
// 13.000 -> "13"
func FloatText(f float64) string {
	s := strconv.FormatFloat(f, 'f', 1, 32)
	s = strings.TrimSuffix(s, ".0")
	return s
}

func RomanNumber(n uint) string {
	if n == 0 {
		return " - "
	}
	var a = [][]string{
		{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
		{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
		{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
		{"", "M", "MM", "MMM"},
	}
	var i = a[3][int(n/1000)]
	var j = a[2][int(n%1000/100)]
	var k = a[1][int(n%100/10)]
	var l = a[0][n%10]
	return i + j + k + l
}

//ConvertTextToHtml will convert plain text(usually from textarea) into typography html.
func ConvertTextToHtml(s string) string {
	s = strings.Trim(s, " ")
	s = strings.Trim(s, "\n")
	s = html.EscapeString(s)
	s = strings.ReplaceAll(s, "\n", "<br />")
	return s
}

func GenerateRandomString(l uint, source string) string {
	b := make([]byte, l)
	sl := len(source)
	for i := range b {
		b[i] = source[rand.Intn(sl)]
	}
	return string(b)
}

func MassText(m float64) string {
	switch {
	case m < 10000:
		return FloatText(m) + "g"
	case m < 10000000:
		return FloatText(m/1000) + "kg"
	default:
		return FloatText(m/10000000) + "t"
	}
}

func Link(href string, title string) string {
	return fmt.Sprintf("<a href=\"%v\">%v</a>", href, title)
}

func RandBetween(min int, max int) int {
	return rand.Intn(max-min+1) + min
}
